import Vue from 'vue';

/**
 * 时间格式化
 */
Vue.filter('timestampToFormat', (timestamp, formatType) => {
  if (timestamp == '' || timestamp == undefined || timestamp == 'undefined' || timestamp == null) {
    return '';
  }
  const dateTime = new Date(parseInt(timestamp));
  let backTime = '';
  const year = dateTime.getFullYear(); // 获取年
  const month = dateTime.getMonth() + 1; // 获取月
  const date = dateTime.getDate(); // 获取日
  const hour = dateTime.getHours(); // 获取时
  const minute = dateTime.getMinutes(); // 获取分
  const second = dateTime.getSeconds(); // 获取秒
  switch (formatType) {
    case '1':
      backTime = `${year}年${zeroFill(month)}月${zeroFill(date)}日`;
      break;
    case '2':
      backTime = `${year}-${zeroFill(month)}-${zeroFill(date)} ${zeroFill(hour)}:${zeroFill(minute)}:${zeroFill(second)}`;
      break;
    case '3':
      backTime = `${year}-${zeroFill(month)}-${zeroFill(date)}`;
      break;
    case '4':
      backTime = `${year}-${zeroFill(month)}-${zeroFill(date)} ${zeroFill(hour)}:${zeroFill(minute)}`;
      break;
    default:
      backTime = `${year}-${month}-${date}`;
      break;
  }
  return backTime;
});


Vue.filter('fileSplice', (s) => {
  s = s.substring(2, s.length - 1);
  return s;
});

/**
 * 数字字符串补零
 *
 * @param num
 * @returns {*}
 */
function zeroFill(num) {
  if (num > 0 && num < 10 || num.toString().length == 1 && num == 0) {
    return `0${num}`;
  }

  return num;
}

/**
 * 关键字
 */
Vue.filter('searchKey', (name, key) => {
  const str = `<span style="color:#007AFF">${key}</span>`;
  return name.replace(key, str);
});

/**
 * 输入计数器
 */
Vue.filter('inputCounter', (inputContent) => {
  if (!inputContent) {
    return 0;
  }
  const matchCounter = inputContent.match(/\r|\n/g) || [];
  return inputContent.length + matchCounter.length;
});

/**
 * 字符串截取
 */
Vue.filter('ellipsisStr', (val, length) => {
  if (val.length > length) {
    return `${val.substring(0, length)}...`;
  }
  return val;
});
